package org.saxonextensions.eml.emitter;

import net.sf.saxon.trans.XPathException;
import org.saxonextensions.eml.emitter.MailSessionFactory;
import org.saxonextensions.eml.emitter.AbstractEmailEmitter;

import javax.mail.Session;
import java.io.OutputStream;

/**
 * This is the basic implementation that serialize received message into an .eml file.
 *
 * @author Ivan Latysh IvanLatysh@yahoo.ca
 * @since 21-Jun-2004 8:05:04 PM
 */
public class EMLEmitter extends AbstractEmailEmitter {

  /**
   * Handle the message
   */
  protected void messageReceived() throws Exception {
    // serialize
    message.writeTo(getOutputStream());
  }

  /** {@inheritDoc} */
  protected Session getSession() throws Exception {
    if (null==session) session= MailSessionFactory.getSession();
    return session;
  }

  /**
   * Before returning the output stream make sure that it is not null
   *
   * @return output stream
   */
  public OutputStream getOutputStream() {
    try {
      // ensure that we have a result stream
      if (null==streamResult.getOutputStream()) {
        setWriter(null);
        makeWriter();
      }
    } catch (XPathException e) {
      e.printStackTrace();
    }
    return super.getOutputStream();
  }

}